import React from "react";
import { Drawer, Button, Card, Input, Select, Row, Col, message, Image } from 'antd';
import { CheckOutlined, PlusSquareOutlined } from '@ant-design/icons';
const { Option } = Select;
const ipcRenderer = window.require('electron').ipcRenderer;
const findPathFromWxml = require('./wxmlTools');
// const { xmlString } = require('./wxmlData');
// const { xmlString } = require('./homewxml');

class CreateElement extends React.Component {
	state = { visible: false, childrenDrawer: false };

	showDrawer = () => {
		this.setState({
			wxml: '', //节点转换成字符串
			pagePath: '', //当前路径
			visible: true,
			identify: '12',
			eventType: 'tap',
			elementType: 'text',
			elements: null,
			selectElement: null,
			selectElementInfo: '',
			params: '',
			showParams: false,
			events: [], //所有展示的事件
			validate: {
				type: 'text',
				value: '',
				mode: 'equal'
			}
		});
	};
	componentDidMount() {
		this.watchEvent();
	}
	watchEvent = () => {
		ipcRenderer.on('get-xml-finish', (event, data, err) => {
			if (err) {
				message.error(err);
			}
			const { wxml, path } = data;
			const { identify, elementType } = this.state;
			const elements = findPathFromWxml(wxml, elementType, identify);
			console.log("find result : ", elements)
			this.setState({
				wxml,
				elements,
				pagePath: path
			}, () => {
				if (elements.length === 1) {
					this.changeElement(0);
				}

			})
		})

		ipcRenderer.on('element-info-finish', (event, selectElementInfo, err) => {
			if (err) {
				message.error(err);
			}
			selectElementInfo.text && (selectElementInfo.text = selectElementInfo.text.substring(0, 15))
			this.setState({
				selectElementInfo
			})
		})

	}

	onClose = () => {
		this.setState({
			visible: false,
		});
	};
	/**
	 * 查找元素
	 */
	findElement = async () => {
		const { identify } = this.state;
		if (!identify) {
			this.setState({
				elements: []
			})
			return;
		}
		ipcRenderer.send('get-xml')
		// --- mock get-xml-finish -----
		// const { elementType } = this.state;
		// const elements = findPathFromWxml(xmlString, elementType, identify);
		// console.log("find result : ", elements)
		// this.setState({
		// 	elements
		// }, () => {
		// 	if (elements.length == 1) {
		// 		this.changeElement(0);
		// 	}

		// })

	}
	/**
	 * 元素标识
	 * @param {*} e 
	 */
	identifyChange = e => {
		const identify = e.target.value;
		this.setState({
			identify
		})
	}
	/**
	 * 元素节点类型
	 * @param {*} elementType 
	 */
	typeChange = elementType => {
		const { identify } = this.state;
		this.setState({
			elementType
		}, () => {
			if (identify) {
				this.findElement()
			}

		})
	}
	/**
	 * 事件类型
	 * @param {*} event 
	 */
	changeEventType(eventType) {
		console.log("事件：", eventType)
		const showParams = Boolean(~['input', 'scrollTo', 'waitFor', 'swiper'].indexOf(eventType))
		this.setState({ eventType, showParams })
	}
	/**
	 * 改变参数
	 * @param {*} params 
	 */
	changeParams(params) {
		this.setState({ params })
	}
	/**
	 * 通过确定的元素查找所在它class的序号
	 */
	findElementIndex(element) {
		const { id, className } = element;
		if (!id || !className) {
			return message.error("元素查找错误")
		}
		const { wxml } = this.state;
		const elements = findPathFromWxml(wxml, 'class', className);
		let elementIndex;
		elements.forEach((ele, index) => {
			if (ele.id === id) {
				elementIndex = index;
			}
		})
		return elementIndex;
	}
	/**
	 * 改变选中的元素
	 * @param {*} index 
	 */
	changeElement(index) {
		let events = [];
		const { elements } = this.state;
		const element = elements[index];
		const type = element.allPath && element.allPath[element.allPath.length - 1]
		element.type = type;
		if (!type) throw Error('节点选取错误');
		switch (type) {
			case 'input': events = ['input', 'clear', 'focus']; break;
			case 'view':
			case 'text':
			case 'image': events = ['tap', 'longpress']; break;
			case 'scroll-view': events = ['scrollTo']; break;
			case 'swiper': events = ['swiper']; break;
			default: return;

		}

		elements[index].index = this.findElementIndex(element);
		ipcRenderer.send('element-info', element);
		this.setState({
			selectElement: element,
			events
		})
	}

	add() {
		const { elementType, identify, selectElement, eventType, params, showParams } = this.state;
		const { generCode } = this.props;
		if (!generCode.hasInit) {
			generCode.exec('start-app')
		}
		if (!generCode.tests.length) {
			generCode.tests.push({ className: [], code: [] })
		}
		const element = {
			params: showParams ? params.split(',') : '',
			type: elementType,
			selector: identify,
			event: eventType,
			...selectElement
		}
		generCode.execTest(element);
		message.success('添加成功');
	}
	/**
	 * 添加测试用例
	 */
	testCreate() {
		const { elementType, identify, selectElement, eventType, params, showParams } = this.state;
		const { generCode } = this.props;
		//
		let type = {
			'text': '文本',
			'id': 'id',
			'class': '类',
			'tagName': '标签类型',
		}[elementType]
		let event = {
			'tap': '点击',
			'longpress': '长按',
			'scrollTo': '滚动',
			'validate': '验证',
			'waitFor': '等待',
			'input': '输入',
		}[eventType]
		generCode.addEvent({
			id: selectElement.id,
			type: event,
			eventType,
			identify: `${type}：${identify}`,
			params: showParams ? params : '',
		});
		message.success('添加成功');
	}

	changeValidate(type, value) {
		const { validate } = this.state;
		validate[type] = value;
		this.setState({ validate })
	}
	validate() {
		let result = false;
		const { validate, selectElementInfo, pagePath } = this.state;
		const { type, mode, value } = validate;
		// selectElementInfo.text = selectElementInfo.content;
		selectElementInfo.pagePath = pagePath;
		if (mode === 'equal') {
			result = value === (selectElementInfo && selectElementInfo[type]);
		} else {
			result = Boolean(selectElementInfo && ~selectElementInfo[type].indexOf(value))
		}

		result ? message.success("验证成功") : message.warn("验证失败")
	}

	render() {
		const { identify, elements, eventType, showParams, selectElement, events = [], selectElementInfo } = this.state;
		const selectBefore = (
			<Select defaultValue="文本" className="select-before" onChange={this.typeChange.bind(this)}>
				<Option value="text">文本</Option>
				<Option value="id">id</Option>
				<Option value="class">class</Option>
			</Select>
		);
		const searchBtn = (<Row size="small" onClick={this.findElement.bind(this)}>查找元素</Row>)

		return (
			<>
				{/* <Button type="primary" onClick={this.showDrawer}>
					4 - 添加事件
        		</Button> */}
				<PlusSquareOutlined onClick={this.showDrawer} />
				<Drawer
					title="添加事件"
					width={520}
					closable={false}
					onClose={this.onClose}
					visible={this.state.visible}
				>


					< Card title="目标元素">
						<Input addonBefore={selectBefore} addonAfter={searchBtn} value={identify} onChange={this.identifyChange.bind(this)} />
						<Row>
							{
								elements && elements.length ? <div style={{ width: '100%' }}>
									<div style={{ color: 'green' }}>共找到{elements.length}个元素：</div>
									{
										elements.map((item, index) => (
											<div style={{ width: '100%', backgroundColor: selectElement && (selectElement.id === item.id) ? '#f8f8f8' : '' }} key={index} onClick={() => this.changeElement(index)}>
												{
													item && item.allPath && <span span="4" style={{ marginRight: '20px' }}>元素类型 : {item.allPath[item.allPath.length - 1]}</span>
												}

												{
													item && item.content && <label span="4" style={{ marginRight: '20px' }}>文案 : <span style={{ color: 'gray' }}>{item.content}</span></label>
												}
												{
													selectElement && (selectElement.id === item.id) ? <CheckOutlined style={{ float: 'right', color: 'green' }} /> : ''
												}
											</div>
										))
									}
								</div> : <div style={{ color: 'red' }}>
										请选择目标元素
								</div>
							}

						</Row>
						{
							selectElementInfo && < Card title="详情">
								<div >
									{
										Object.keys(selectElementInfo).map((key, index) => (
											<div key={index}>{key}：<label style={{ color: "green" }}>
												{selectElementInfo[key]}
											</label></div>
										))
									}
									{
										selectElementInfo.tagName === 'image' && <Image src={selectElementInfo.src} style={{ maxWidth: '100%' }}></Image>
									}
								</div>
							</Card>
						}

					</Card>
					{
						selectElement ? < Card title="操作">
							{
								~events.indexOf('tap') ? <Button type={eventType === 'tap' ? 'primary' : 'default'} onClick={() => this.changeEventType('tap')}>点击</Button> : ''
							}

							{
								~events.indexOf('longpress') ? <Button type={eventType === 'longpress' ? 'primary' : 'default'} onClick={() => this.changeEventType('longpress')}>长按</Button> : ''
							}
							{
								~events.indexOf('input') ? <Button type={eventType === 'input' ? 'primary' : 'default'} onClick={() => this.changeEventType('input')}>输入</Button> : ''
							}
							{
								~events.indexOf('scrollTo') ? <Button type={eventType === 'scrollTo' ? 'primary' : 'default'} onClick={() => this.changeEventType('scrollTo')}>滚动</Button> : ''
							}
							{
								~events.indexOf('swiper') ? <Button type={eventType === 'swiper' ? 'primary' : 'default'} onClick={() => this.changeEventType('scroll')}>修改轮播序号</Button> : ''
							}
							<Button type={eventType === 'waitFor' ? 'primary' : 'default'} onClick={() => this.changeEventType('waitFor')}>等待</Button>
							<Button type={eventType === 'valid' ? 'primary' : 'default'} onClick={() => this.changeEventType('valid')}>验证</Button>
							<Button type={eventType === 'if' ? 'primary' : 'default'} onClick={() => this.changeEventType('if')}>条件判断</Button>
							<Button type={eventType === 'for' ? 'primary' : 'default'} onClick={() => this.changeEventType('for')}>循环</Button>
						</Card> : ''
					}


					{
						showParams ? < Card title="参数">
							<Row>
								{
									eventType === 'scrollTo' ? '滚动到' : '输入内容'
								}
								：<Input onChange={e => this.changeParams(e.target.value)} placeholder={eventType === 'scrollTo' ? '(x,y)' : ''} />
							</Row>
						</Card> : ''
					}
					{
						eventType === 'valid' && <Card title="验证">
							<Row>
								<Col span={7}>
									<Select defaultValue="文本内容" className="select-before" onChange={e => this.changeValidate('type', e)}>
										<Option value="text">文本内容</Option>
										<Option value="pagePath">页面路径</Option>
										<Option value="className">className</Option>
										<Option value="tagName">tagName</Option>
									</Select>

								</Col>
								<Col span={5}>
									<Select defaultValue="等于" className="select-before" onChange={e => this.changeValidate('mode', e)}>
										<Option value="equal">等于</Option>
										<Option value="contain">包含</Option>
									</Select>

								</Col>
								<Col span={12}>
									<Input onChange={e => this.changeValidate('value', e.target.value)} placeholder={eventType === 'scrollTo' ? '(x,y)' : ''} />
								</Col>
							</Row>
							<Button type="primary" onClick={() => this.validate()} style={{ marginTop: 30 }}>验证</Button>
						</Card>
					}

					< Card title="操作">

						<Button onClick={() => this.add()} disabled={!selectElement}>测试</Button>

						<Button type="primary" onClick={() => this.testCreate()} style={{ marginLeft: 30 }} disabled={!selectElement}>添加</Button>

					</Card>
				</Drawer>
			</>
		);
	}
}

export default CreateElement;